<template>
  <div class="join bg-base-100 flex justify-center mt-8" v-show="totalPages">
    <button class="join-item btn" @click="prevPage"><Icon name="solar:map-arrow-left-bold-duotone" size="20"/></button>
    <template v-if="currentPage > 4">
      <button class="join-item btn" @click="goToPage(1)">1</button>
      <button class="join-item btn" @click="goToPage(currentPage-5)">...</button>
    </template>
    <template v-for="page in displayedPages" :key="page">
      <button
          class="join-item btn"
          :class="{ 'btn-active': page === currentPage }"
          @click="goToPage(page)">
        {{ page }}
      </button>
    </template>
    <template v-if="currentPage < totalPages - 3">
      <button class="join-item btn" @click="goToPage(currentPage+5)">...</button>
      <button class="join-item btn" @click="goToPage(totalPages)">{{ totalPages }}</button>
    </template>
    <button class="join-item btn" @click="nextPage"><Icon name="solar:map-arrow-right-bold-duotone" size="20"/></button>
  </div>
</template>

<script setup lang="ts">
import {ref} from 'vue';

const emits = defineEmits(["changePage"]);
const props = defineProps({
  totalNum: {
    type: Number,
    required: true,
  },
  totalPages: {
    type: Number,
    required: true,
  },
  pageSize: {
    type: Number,
    require: true,
    default: 9,
  },
  pageNum: {
    type: Number,
    require: true,
    default: 1,
  },
});
const currentPage = ref(props.pageNum);
const prevPage = () => {
  if (props.pageNum > 1) {
    currentPage.value = currentPage.value - 1;
    emits('changePage', currentPage.value);
  }
};
const goToPage = (pageNum: number) => {
  if (pageNum > props.totalPages) {
    currentPage.value = props.totalPages;
  } else if (pageNum < 1) {
    currentPage.value = 1;
  } else {
    currentPage.value = pageNum
  }
  emits('changePage', currentPage.value);
};
const nextPage = () => {
  if (props.pageNum < props.totalPages) {
    currentPage.value = currentPage.value + 1;
    emits('changePage', currentPage.value);
  }
};
const displayedPages = computed(() => {
  if (currentPage.value <= 4) {
    return Array.from({length: Math.min(5, props.totalPages)}, (_, i) => i + 1);
  } else if (currentPage.value >= props.totalPages - 3) {
    return Array.from({length: Math.min(5, props.totalPages)}, (_, i) => props.totalPages - 4 + i);
  } else {
    return [currentPage.value - 2, currentPage.value - 1, currentPage.value, currentPage.value + 1, currentPage.value + 2];
  }
});
</script>